<?php
namespace Home\Controller;
use Think\Controller;
class CommonController extends Controller {

	public function test(){
		// echo time()+60*60*2;
		// $returnArr = show_dragon();
		// echo "<pre>";print_r($returnArr);
        sendToMobile('183111111',1);   
	}

	//400 错误请求页面
	public function BadRequest(){
		$this->display('404');
	}


	//未开放页面
	public function notopen(){
        $type = $_REQUEST['type'];
        if ($type == 1) {//交易积分购买
            $errormsg = '请到交易大厅购买';
            $time = '';
        }elseif ($type == 11) {
            $hallStart = C('hallStart');
            $hallEnd = C('hallEnd');
            $errormsg = '当前时间暂未开放';
            $time = '开放时间：'.$hallStart.' - '.$hallEnd;
        }else{//秘钥购买
            $lowestTime = C('lowestTime');
            $biggestTime = C('biggestTime');
            $errormsg = '当前时间暂未开放';
            $time = '开放时间：'.$lowestTime.' - '.$biggestTime;
        }
        $this->assign('errormsg',$errormsg);
        $this->assign('time',$time);
		$this->display();
	}


	/**
	 * [logout 退出登录]
	 * @return [type] [description]
	 */
    public function logout(){

        $this->redirect('Common/login');
    }

	/**
	 * [login 登录页面]
	 * @return [type] [description]
	 */
	public function login(){
        session('uid',null);
        // echo "111";
		$this->display();
	}


	/**
	 * [ctrl_login 登录执行函数]
	 * @return [type] [description]
	 */
	public function ctrl_login(){
		if(IS_AJAX){
			$account = trim($_REQUEST['account']);
			$password = trim($_REQUEST['password']);
			$code = trim($_REQUEST['code']);

			$m_user = M('User');
			$m_read = M('Read');
			$m_news = M('News');

			//验证图片码
			$verify = new \Think\Verify();
			if($verify->check($code)===true){
				//查询账号是否存在
				$where['account'] = $account;
				$userInfo = $m_user->where($where)->find();
				if ($userInfo['id']) {
					if ($userInfo['status'] == 2) {
						$this->ajaxReturn(array(
		                    'code'=>0,
		                    'msg' => '账号冻结，无法登录'
		                ));
					}else{
						
						if (md5($password) == $userInfo['password']) {
							session('uid',$userInfo['id']);
							session('overtime',(time()+60*60*C('overtime')));

							//新闻公告
							$read = $m_read->where(array('u_id'=>$userInfo['id']))->order('id asc')->field('n_id')->select();
							
							if (!empty($read)) {
								$n_ids = array_column($read, 'n_id');
								$str_nids = implode(',', $n_ids);
							}else{
								$str_nids = '';
							}
							//新发布的新闻公告
							$where_new['id'] = array('not in',$str_nids);
							$newList = $m_news->where($where_new)->order('id asc')->field('id')->select();

							$add['u_id'] = $userInfo['id'];
							$add['status'] = 0;//标记未读
							foreach ($newList as $key => $value) {
								$add['n_id'] = $value['id'];
								$m_read->add($add);
							}

							$this->ajaxReturn(array(
			                    'code'=>1,
			                    'msg' => '登录成功'
			                ));
						}else{
							$this->ajaxReturn(array(
			                    'code'=>0,
			                    'msg' => '密码错误'
			                ));
						}
					}
				}else{
					$this->ajaxReturn(array(
	                    'code'=>0,
	                    'msg' => '账号不存在'
	                ));
				}
			}else{
				$this->ajaxReturn(array(
                    'code'=>0,
                    'msg' => '验证码错误！'
                ));
			}
		}else{
			$this->redirect('Common/BadRequest');
		}
	}


	/**
	 * [verify 图片验证码]
	 * @return [type] [description]
	 */
	public function verify()
   	{
		$Verify = new \Think\Verify();
		$Verify->codeSet = "1234567890";
		$Verify->fontSize = 30;
		$Verify->length   = 4;
		$Verify->useNoise = true;
		$Verify->useCurve = false;
		$Verify->entry();
   	}


   	/**
     * [UploadPic 上传图片]
     */
    public function UploadPic(){
        
        if (IS_AJAX) {
                
        
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize   =     31457280 ;// 设置附件上传大小30M
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
            $upload->savePath  =     ''; // 设置附件上传（子）目录
            $upload->subName   =     array('date','Ymd');
            // 上传文件 
            $info   =   $upload->upload();
            if(!$info) {// 上传错误提示错误信息
                $this->ajaxReturn(array(
                    'code'=>0,
                    'msg'=>$upload->getError(),
                ));
            }else{// 上传成功
                
                $url = '/Uploads/'.$info['file']['savepath'].$info['file']['savename'];
                      
                $this->ajaxReturn(array(
                    'code'=>1,
                    'msg'=>'上传成功',
                    'url'=>$url,
                ));
            }
        }
    }


    /*自动数据访问*/
    public function autoUpdate(){

        $m_gamessc = M('Game_ssc');

        $src = C('KCW_SRC');//api接口地址
        //防止GET本地缓存，增加随机数
        $src .= '&rows=3'.(strpos($src,'?')>0 ? '&':'?').'_='.time();
        $html = file_get_contents($src);
        $json = json_decode($html,true);

        if (isset($json['rows'])){
        	$newCode = array();
            // echo "<pre>";
            // print_r($json);
            $jsondata = array_reverse($json['data']);

            
            foreach($jsondata as $key => $r){
                $expect = preg_replace("/^(\d{8})(\d{3})$/","\\1-\\2",$r['expect']);
                $opencode = $r['opencode'];
                $opentime = $r['opentime'];

                $expect_arr = explode('-', $expect);

                $where_ssc['code'] = $expect_arr['0'];
                $where_ssc['codenum'] = $expect_arr['1'];
                $sscInfo = $m_gamessc->where($where_ssc)->getfield('id');
                
                if (!$sscInfo) {
                    $add['code'] = $expect_arr['0'];
                    $add['codenum'] = $expect_arr['1'];
                    $add['num'] = $opencode;
                    $add['createtime'] = $opentime;
                    $add['str_time'] = $r['opentimestamp'];

                    $m_gamessc->add($add);

                    // 添加长龙
                    func_dragon($opencode);
                }

            }
            // 更新所有用户未开奖的结果
            func_allUserGuess();
        }else{
        	$this->redirect('Common/autoUpload');
        }
    }


    /**
     * [promote 推广注册页面]
     * @return [type] [description]
     */
    public function promote(){
    	$uid = $_REQUEST['id'];
    	$m_user = M('User');
    	$where['id'] = $uid;
    	$topAccount = $m_user->where($where)->getfield('account');

    	$this->assign('topAccount',$topAccount);
    	$this->display();
    }



    /**
     * [ctrl_register 注册会员]
     * @return [type] [description]
     */
    public function ctrl_register(){
        if(IS_AJAX){
            $regAccount = trim($_REQUEST['regAccount']);
            $topAccount = trim($_REQUEST['topAccount']);
            $truename = trim($_REQUEST['truename']);
            $phone = trim($_REQUEST['phone']);
            $password = trim($_REQUEST['password']);
            $confirm_password = trim($_REQUEST['confirm_password']);
            $safe_password = trim($_REQUEST['safe_password']);
            $confirm_safe_password = trim($_REQUEST['confirm_safe_password']);
            // $regMoney = trim($_REQUEST['regMoney']);

            $m_user = M('User');

            // 注册账号信息
            $where_reg['account'] = $regAccount;
            $existingInfo = $m_user->where($where_reg)->find();
            //推荐人账号信息
            $where_top['account'] = $topAccount;
            $topInfo = $m_user->where($where_top)->find();

            if (empty($regAccount) || empty($topAccount) || empty($truename) || empty($phone) || empty($password) || empty($confirm_password) || empty($safe_password) || empty($confirm_safe_password) ) {
                $this->ajaxReturn(array(
                    'code'=>0,
                    'msg' => '信息不完整，请完善'
                ));
            }else{
                if ($existingInfo['id']) {//已存在注册账号
                    $this->ajaxReturn(array(
                        'code'=>0,
                        'msg' => '注册的账号已存在，请重新输入登录账号'
                    ));
                }else{
                    if ($topInfo['id']) {//推荐人账号正确
                        if ($topInfo['status'] == 0) {
                            $this->ajaxReturn(array(
                                'code'=>0,
                                'msg' => '推荐账号未激活，无法注册'
                            ));
                        }elseif ($topInfo['status'] == 2) {
                            $this->ajaxReturn(array(
                                'code'=>0,
                                'msg' => '推荐账号被冻结，无法注册'
                            ));
                        }else{

                            if (!isMobile($phone)) {
                                $this->ajaxReturn(array(
                                    'code'=>0,
                                    'msg' => '手机格式不正确'
                                ));
                            }else{
                                $where_phone['phone'] = $phone;
                                $phoneInfo = $m_user->where($where_phone)->find();
                                if ($phoneInfo['id']) {
                                    $this->ajaxReturn(array(
                                        'code'=>0,
                                        'msg' => '手机号已注册，请重新输入手机号'
                                    ));
                                }else{
                                  
                                    if ($password != $confirm_password) {
                                        $this->ajaxReturn(array(
                                            'code'=>0,
                                            'msg' => '两次登录密码不一致'
                                        ));
                                    }else{
                                        if (strlen($password) < 6 || strlen($confirm_password) < 6) {
                                            $this->ajaxReturn(array(
                                                'code'=>0,
                                                'msg' => '登录密码长度过短，建议长于>=6'
                                            ));
                                        }else{
                                            if ($safe_password != $confirm_safe_password) {
                                                $this->ajaxReturn(array(
                                                    'code'=>0,
                                                    'msg' => '两次交易密码不一致'
                                                ));
                                            }else{
                                                if (strlen($safe_password) < 6 || strlen($confirm_safe_password) < 6) {
                                                    $this->ajaxReturn(array(
                                                        'code'=>0,
                                                        'msg' => '交易密码长度过短，建议长于>=6'
                                                    ));
                                                }else{
                                                    $add['account'] = $regAccount;
                                                    $add['password'] = md5($password);
                                                    $add['safe_password'] = md5($safe_password);
                                                    $add['truename'] = $truename;
                                                    $add['phone'] = $phone;
                                                    // $add['register_money'] = $regMoney;
                                                    $add['top_id'] = $topInfo['id'];
                                                    $add['createtime'] = time();

                                                    $res = $m_user->add($add);
                                                    if ($res) {
                                                        //添加直推人数、团队人数
                                                        topPeople($topInfo['id']);
                                                        teamPeople($topInfo['id']);
                                                        $this->ajaxReturn(array(
                                                            'code'=>1,
                                                            'msg' => '注册成功'
                                                        ));
                                                    }else{
                                                        $this->ajaxReturn(array(
                                                            'code'=>0,
                                                            'msg' => '注册失败'
                                                        ));
                                                    }
                                                }
                                            }
                                        }
                                    }  
                                }
                            }
                        }
                    }else{
                        $this->ajaxReturn(array(
                            'code'=>0,
                            'msg' => '推荐人账号不存在，请重新输入'
                        ));
                    }
                }

            }
        }else{
            $this->redirect('Common/login');
        }
    }


    /**
     * [forget 忘记密码页面]
     * @return [type] [description]
     */
    public function forget(){
        $this->display();
    }


    /**
     * [ctrl_forget 重置密码]
     * @return [type] [description]
     */
    public function ctrl_forget(){
        if (IS_AJAX) {
            // print_r($_REQUEST);die();
            $phone = trim($_REQUEST['phone']);
            $code = trim($_REQUEST['code']);
            $password = trim($_REQUEST['password']);
            $confirm_password = trim($_REQUEST['confirmpassword']);

            $m_user = M('User');

            if (empty($phone) || empty($code) || empty($password) || empty($confirm_password) ) {
                $this->ajaxReturn(array(
                    'code'=>0,
                    'msg' => '信息不完整，请完善'
                ));
            }else{
                if (!isMobile($phone)) {
                    $this->ajaxReturn(array(
                        'code'=>0,
                        'msg' => '手机格式不正确'
                    ));
                }else{
                    if ($_SESSION['forgetcode'] != $code) {
                        $this->ajaxReturn(array(
                            'code'=>0,
                            'msg' => '验证码不正确'
                        ));
                    }else{
                        if (strlen($password) < 6 || strlen($confirm_password) < 6) {
                            $this->ajaxReturn(array(
                                'code'=>0,
                                'msg' => '新密码长度过短，建议长于>=6'
                            ));
                        }else{
                            if ($password != $confirm_password) {
                                $this->ajaxReturn(array(
                                    'code'=>0,
                                    'msg' => '两次登录密码不一致'
                                ));
                            }else{
                                $where['phone'] = $phone;
                                $userInfo = $m_user->where($where)->find();
                                if ($userInfo['id']) {
                                    if (md5($password) == $userInfo['password']) {
                                        $this->ajaxReturn(array(
                                            'code'=>0,
                                            'msg' => '新密码与旧密码相同，无法重置'
                                        ));
                                    }else{
                                        $save['password'] = md5($password);
                                        $res = $m_user->where(array('id'=>$userInfo['id']))->save($save);
                                        if ($res) {
                                            $this->ajaxReturn(array(
                                                'code'=>1,
                                                'msg' => '重置密码成功'
                                            ));
                                        }else{
                                            $this->ajaxReturn(array(
                                                'code'=>0,
                                                'msg' => '重置失败，请刷新页面重新操作'
                                            ));
                                        }
                                    }
                                }else{
                                    $this->ajaxReturn(array(
                                        'code'=>0,
                                        'msg' => '手机号不存在'
                                    ));
                                }
                            }
                        }
                    }
                }
            }
        }else{
            $this->redirect('Common/BadRequest');
        }
    }


    /**
     * [ctrl_sendmsg 发送验证码]
     * @return [type] [description]
     */
    public function ctrl_sendmsg(){
        if (IS_AJAX) {
            // print_r($_REQUEST);die();
            $phone = trim($_REQUEST['phone']);
            $type = $_REQUEST['type'];

            if (empty($phone) || empty($type)) {
                $this->ajaxReturn(array(
                    'code'=>0,
                    'msg' => '信息不完整，无法发送验证码'
                ));
            }else{
                $res = sendToMobile($phone,$type);
                if ($res == 'OK') {
                    $this->ajaxReturn(array(
                        'code'=>1,
                        'msg' => '短信发送成功'
                    ));
                }else{
                    $this->ajaxReturn(array(
                        'code'=>0,
                        'msg' => '短信发送失败'
                    ));
                }
            }
        }else{
            $this->redirect('Common/BadRequest');
        }
    }

   	
}